import React, { Component } from 'react';
import { connect } from 'dva';
import { Row, Col, Card, Badge, Table, Radio } from 'antd';
import DescriptionList from 'components/DescriptionList';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './FamilyMemberDetail.less';
import {
  yuan,
  Pie,
} from 'components/Charts';

const { Description } = DescriptionList;
const operationTabList = [
  {
    key: 'tab1',
    tab: '个人信息',
  },
  {
    key: 'tab2',
    tab: '子孙图谱',
  },
];

const columns = [
  {
    title: '姓名',
    dataIndex: 'name',
    key: 'name',
    render: (text, record) => <a href={'family_member_detail?id=' + record.id}>{text}</a>
  },
  {
    title: '性别',
    dataIndex: 'gender',
    key: 'gender',
    render: text =>
      text === 'M' ? (
        <Badge status="success" text="男" />
      ) : (
        <Badge status="error" text="女" />
      ),
  },
  {
    title: '属相',
    dataIndex: 'zodiac',
    key: 'zodiac',
  },
  {
    title: '出生日期',
    dataIndex: 'birthDate',
    key: 'birthDate',
  },
  {
    title: '出生地',
    dataIndex: 'birthPlace',
    key: 'birthPlace',
  },
  {
    title: '职业',
    dataIndex: 'occupation',
    key: 'occupation',
  },
];

export default class FamilyMemberDetail extends Component {
  state = {
    operationkey: 'tab1',
  };

  onOperationTabChange = key => {
    this.setState({ operationkey: key });
  };

  parseUrlParam = (name, url) => {
    if (!url) {
      url = window.location.href;
    }
    name = name.replace(/[\\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
    results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
      return decodeURIComponent(results[2].replace(/\\+/g, " "));
  }

  render() {
    const contentList = {
      tab1: (
        <FamilyMemberProfile memberId={this.parseUrlParam('id')}/>
      ),
      tab2: (
        <FamilyMemberGroupInfo memberId={this.parseUrlParam('id')}/>
      ),
    };

    return (
      <PageHeaderLayout
      >
        <Card
          className={styles.tabsCard}
          bordered={false}
          tabList={operationTabList}
          onTabChange={this.onOperationTabChange}
          loading={false}
        >
          {contentList[this.state.operationkey]}
        </Card>
      </PageHeaderLayout>
    );
  }
}

@connect(({ profile, loading }) => ({
  profile,
  loading: loading.effects['profile/fetchAdvanced'],
}))
export class FamilyMemberProfile extends Component {

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'profile/fetchAdvanced',
      payload: this.props.memberId,
    });
  }

  render() {
    let gender = this.props.profile.gender === 'M' ? (
      <Badge status="success" text="男" />
    ) : (
      <Badge status="error" text="女" />
    )
    let hasContactInfo = this.props.profile.phoneNumber !== null
                      || this.props.profile.office !== null
                      || this.props.profile.homeAddress !== null
                      || this.props.profile.schoolMsg !== null
                      || this.props.profile.note !== null;
    return (
      <div>
        <Card
          bordered={false}
        >
          {(this.props.profile.deathDate !== null && this.props.profile.deathDate !== '') ?
            <DescriptionList size="large" title="基本信息" style={{ marginBottom: 32 }}>
              <Description term="姓名">{this.props.profile.name}</Description>
              <Description term="性别">{gender}</Description>
              <Description term="属相">{this.props.profile.zodiac}</Description>
              <Description term="配偶">{this.props.profile.spouse}</Description>
              <Description term="出生日期">{this.props.profile.birthDate}</Description>
              <Description term="逝世日期">{this.props.profile.deathDate}</Description>
              <Description term="出生地">{this.props.profile.birthPlace}</Description>
              <Description term="职业">{this.props.profile.occupation}</Description>
            </DescriptionList>
          :
            <DescriptionList size="large" title="基本信息" style={{ marginBottom: 32 }}>
              <Description term="姓名">{this.props.profile.name}</Description>
              <Description term="性别">{gender}</Description>
              <Description term="属相">{this.props.profile.zodiac}</Description>
              <Description term="配偶">{this.props.profile.spouse}</Description>
              <Description term="出生日期">{this.props.profile.birthDate}</Description>
              <Description term="出生地">{this.props.profile.birthPlace}</Description>
              <Description term="职业">{this.props.profile.occupation}</Description>
            </DescriptionList>
          }
          {hasContactInfo ?
            <DescriptionList size="large" title="通讯及其它信息" style={{ marginBottom: 32 }}>
              <Description term="手机号码">{this.props.profile.phoneNumber}</Description>
              <Description term="工作单位">{this.props.profile.office}</Description>
              <Description term="家庭住址">{this.props.profile.homeAddress}</Description>
              <Description term="学历信息">{this.props.profile.schoolMsg}</Description>
              <Description term="其他备注">{this.props.profile.note}</Description>
            </DescriptionList> : null
          }
        </Card>
        <Card
          bordered={false}
        >
          <DescriptionList size="large" title="子女信息" style={{ marginBottom: 32 }}>
            <Table
            pagination={false}
            dataSource={this.props.profile.children}
            columns={columns}
            />  
          </DescriptionList>        
        </Card>
      </div>
    );
  }
}

@connect(({ chart, loading }) => ({
  chart,
  loading: loading.effects['chart/fetch'],
}))
export class FamilyMemberGroupInfo extends Component {
  
  state = {
    groupType: 'gender',
    currentTabKey: '',
  };

  componentDidMount() {
    const { dispatch } = this.props;
    this.props.dispatch({
      type: 'chart/fetch',
      payload: this.props.memberId,
    });
  }

  handleChangeGroupType = e => {
    this.setState({
      groupType: e.target.value,
    });
  };
  
  render() {
    const { chart, loading } = this.props;
    const { groupType, currentTabKey } = this.state;
    const {
      hasChild,
      generations,
      totalNum,
      name,
      gender,
      genderGroupData,
      generationGroupData,
      birthPlaceGroupData,
      occupationGroupData,
      zodiacGroupData,
    } = chart;
    
    if(!hasChild) return (<div className={styles.noData}>暂无数据</div>);

    const groupPieData =
      groupType === 'gender'
        ? genderGroupData
        : groupType === 'generation'
        ? generationGroupData 
        : groupType === 'birthPlace'
        ? birthPlaceGroupData 
        : groupType === 'occupation'
        ? occupationGroupData : zodiacGroupData;

    const headDes = name + (gender === 'M' ? '先生' : '女士') + '育有子孙' + (generations+1) + '代(含自己)，共' + totalNum + '人，其中：';
    return (
      <Row gutter={24}>
        <Col xl={9} lg={24} md={24} sm={24} xs={24}>
          <Card
            bordered={false}
          >
            <DescriptionList size="large" title="统计摘要" style={{ marginBottom: 32 }}>
              <div>{headDes}</div>
              <br/>
              <div>
                {generationGroupData.map((item, index)=>(
                    <div>{item.x}：{item.y}人</div>
                  )
                )}                
              </div>
            </DescriptionList>
          </Card>          
        </Col>  
        <Col xl={15} lg={24} md={24} sm={24} xs={24}>
          <Card
            loading={loading}
            // className={styles.salesCard}
            bordered={false}
            title="分组信息统计"
            // bodyStyle={{ padding: 24 }}
            extra={
              <div className={styles.salesCardExtra}>
                <div className={styles.salesTypeRadio}>
                  <Radio.Group value={groupType} onChange={this.handleChangeGroupType}>
                    <Radio.Button value="gender">性别</Radio.Button>
                    <Radio.Button value="zodiac">属相</Radio.Button>
                    <Radio.Button value="generation">世代</Radio.Button>
                    <Radio.Button value="birthPlace">出生地</Radio.Button>
                    <Radio.Button value="occupation">职业</Radio.Button>
                  </Radio.Group>
                </div>
              </div>
            }
            // style={{ marginTop: 24, minHeight: 509 }}
          >
            <Pie
              hasLegend
              data={groupPieData}
              valueFormat={val => <span dangerouslySetInnerHTML={{ __html: val + "人" }} />}
              height={248}
              lineWidth={4}
            />
          </Card>
        </Col>          
      </Row>
    );
  }
}